<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/7/6 0006
 * Time: 14:04
 */

namespace app\api\controller\v1\member;


use app\api\controller\v1\Member;
use app\currency\service\CitiesService;
use library\tools\Data;
use think\Db;
use think\exception\HttpResponseException;

class OrderPre extends Member
{
    /**
     * 读取预订单并绑定到订单
     * @param $id
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function read($id)
    {
        $order_pre = Db::name('CleanOrderPre')
            ->where([
                ['order_no','eq',$id]
            ])
            ->find();
        empty($order_pre) && $this->error('查询预订单信息失败！');

        $cities = Db::name('Cities')->where('id',$order_pre['cities_id'])->find();
        empty($cities) && $this->error('地址信息查询失败！');
        if($order_pre['status'] == '1')
        {
            $this->get_order_info($order_pre['order_no_set']);
        }
        $unit_price = sysconf('service_unit_price');
        if(empty($unit_price))
        {
            $this->error('请先设置服务单价！');
        }
        $order_no_set = Data::uniqidNumberCode(12);
        $order = [
            'mid' => $this->mid,
            'cid' => $order_pre['cid'],
            'order_no' => $order_no_set,
            'service_date' => $order_pre['service_date'],
            'time_slot' => $order_pre['time_slot'],
            'cities_id' => $order_pre['cities_id'],
            'contact_name' => $order_pre['contact_name'],
            'contact_phone' => $order_pre['contact_phone'],
            'cities_center' => $cities['center'],
            'service_duration' => $order_pre['service_duration'],
            'status' => '3',
            'service_status' => '2',
            'service_start_at' => date('Y-m-d H:i:s'),
            'service_end_at' => date('Y-m-d H:i:s'),
        ];
        //计算订单总价
        $order['total_price'] = $order['service_duration'] * $unit_price;
        //订单待支付金额
        $order['actual_amount'] = $order['total_price'];
        try {
            // 订单数据写入
            Db::transaction(function() use($order,$order_pre,$order_no_set){
                Db::name('CleanOrder')->insert($order);
                if(!Db::name('CitiesMember')->where([
                    ['mid','eq',$this->mid],
                    ['cities_id','eq',$order_pre['cities_id']]
                ])->find())
                {
                    Db::name('CitiesMember')->insert([
                        'mid' => $this->mid,
                        'cities_id' => $order_pre['cities_id'],
                        'contact_name' => $order_pre['contact_name'],
                        'contact_phone' => $order_pre['contact_phone'],
                    ]);
                }
                Db::name('CleanOrderPre')
                    ->where('order_no','eq',$order_pre['order_no'])
                    ->update([
                        'status' => '1',
                        'order_no_set' => $order_no_set
                    ]);
            });
            $this->get_order_info($order_no_set);
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $e) {
            $this->error("创建订单失败，请稍候再试！{$e->getMessage()}");
        }
    }
    protected function get_order_info($order_no)
    {
        $where =[['mid','eq',$this->mid],['order_no','eq',$order_no],['is_deleted','eq',0]];
        //订单信息
        $order = Db::name('CleanOrder')->where($where)->find();
        empty($order) && $this->error('订单信息查询失败！');
        $order['cleaner'] = [];
        if($order['cid'] > 0)
        {
            $order['cleaner'] = Db::name('Cleaner')->where(['id'=>$order['cid']])->find();
        }
        $order['unit_price'] = sysconf('service_unit_price');
        $order['address_txt'] = CitiesService::getAddressText($order['cities_id'],'string');
        //计算赠送积分
        $order['present_integral']=0;
        if($order['is_no_complete'] != 1)
        {
            $PresentIntegralSwitch = sysconf('present_integral_switch');
            if($PresentIntegralSwitch)
            {
                if(!empty($order['cleaner']) && $order['cleaner']['integral_present_num'] > 0)
                {
                    $PresentIntegralRatio = sysconf('present_integral_ratio') ?: 0;
                    if($PresentIntegralRatio > 0)
                    {
                        $order['present_integral'] = floor($order['total_price'] * $PresentIntegralRatio);
                    }
                }
            }
        }
        $this->success('获取订单详情成功！',$order);
    }
}